<template>
	<div class="storage-object-container">
		<el-dialog title="上传对象" v-model="isShowDialog" >
			<el-form ref="uploadFormRef" :model="formData" :rules="formRules" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="上传类型" prop="type">
							<el-select v-model="formData.type" placeholder="请选择上传类型" clearable class="w100">
								<el-option label="本地文件" :value="0"></el-option>
								<el-option label="网络文件" :value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="新建文件夹" prop="businessKey">
							<el-input v-model="formData.businessKey" placeholder="请输入文件夹名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="formData.type == 1">
						<el-form-item label="网络文件" prop="source">
							<el-input v-model="formData.source" placeholder="请输入网络文件地址 http(s)://" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-else>
						<el-upload ref="uploadFileRef" :drag="true" :multiple="false"
							:auto-upload="false"
							:action="upload.action"
							:headers="upload.headers"
							:name="upload.name"
							:file-list="upload.fileList"
							:before-upload="handleBeforeUpload"
							:on-success="handleUploadSuccess"
							:on-error="handleUploadError">
							<el-icon class="el-icon--upload">
								<el-icon-upload-filled></el-icon-upload-filled>
							</el-icon>
							<div class="el-upload__text">
								拖拽文件到此处 或 <em>点击上传</em>
							</div>
							<template #tip>
								<div class="el-upload__tip">
									文件大小最大限制 50MB 以下
								</div>
							</template>
						</el-upload>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit">上 传</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
import { Sign } from '/@/utils/sign';
import { uploadStorage, uploadStorageUrl } from '/@/api/storage/index';
import { verifyStringCode } from '/@/utils/toolsValidate';
export default {
	name: 'storage/upload',
	setup(props, context) {
		const storage_api = import.meta.env.VITE_STORAGE_API as string;
		const uploadFormRef = ref();
		const uploadFileRef = ref();
		const validBusinessKey = (rule, value, callback) => {
			if(value && !verifyStringCode(value)){
				return callback(new Error('文件夹名称格式不正确，只允许字母或数字或下划线组合成5-16个字符'));
			}
			callback();
		}
		const state = reactive({
			isShowDialog: false,
			formData: {
				type: 0,
				source: undefined,
				businessKey : undefined,
			},
			formRules : {
				businessKey: { required: false, validator: validBusinessKey, trigger: 'blur' },
			},
			upload: {
				action: uploadStorageUrl(),
				headers: {
					Authorization : 'Bearer ' + Session.get('token'),
					signature: '',
					secret: '',
					timestamp: 0,
				},
				name: 'file',
				fileList: [],
			},
		});

		// 打开弹窗
		const openDialog = (row?: object) => {
			state.isShowDialog = true;
		};
		// 关闭弹窗
		const closeDialog = (row?: object) => {
			state.isShowDialog = false;
			state.upload.action = '';
			state.upload.fileList = [];
			for(var key in state.formData) {
				state.formData[key] = undefined;
			}
			uploadFormRef.value.resetFields();
		};
		//上传之前
		const handleBeforeUpload = (file) => {
			if(file.size >= 50 * 1024 * 1024){//50M
				ElMessage.error('文件大小最大限制 50MB 以下');
				return false;
			}
			state.upload.action = uploadStorageUrl() + (state.formData.businessKey ? '/' + state.formData.businessKey : '');
			state.upload.headers.Authorization = 'Bearer ' + Session.get('token');
			// 参数签名
			const options = {
				url: `${storage_api}/upload${(state.formData.businessKey ? '/' + state.formData.businessKey : '')}`, 
				data: {
					'file': file.name,
				}
			}
			const { signature, secret, timestamp } = Sign.signature(options);
			state.upload.headers.signature = signature;
			state.upload.headers.secret = secret;
			state.upload.headers.timestamp = timestamp;
		}
		//上传成功
		const handleUploadSuccess = (res) => {
			if(res.code == 0){
				ElMessage.success('上传成功');
				context.emit('submit');
				closeDialog();
			}else{
				ElMessage.error(res.msg);
			}
		};
		const handleUploadError = (error) => {
			ElMessage.error(JSON.parse(error.message)?.msg || '未知错误');
		}
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 上传
		const onSubmit = () => {
			uploadFormRef.value.validate(valid => {
				if(valid){
					if(state.formData.type == 1){
						uploadStorage(state.formData.businessKey, {source: state.formData.source}).then((res) => {
							if(res.code === 0){
								ElMessage.success('上传成功');
								context.emit('submit');
								closeDialog();
							}
						});
					}else{
						uploadFileRef.value!.submit();
					}
				}
			});
		};
		
		return {
			uploadFormRef,
			uploadFileRef,
			openDialog,
			closeDialog,
			handleBeforeUpload,
			handleUploadSuccess,
			handleUploadError,
			onCancel,
			onSubmit,
			...toRefs(state),
		};
	},
};
</script>